# app/core/state.py
import threading
from queue import Queue
import logging

logger = logging.getLogger(__name__)

class AppState:
    def __init__(self):
        self.db_task_queue = Queue()
        self.db_thread = None
        self.safe_db_operation = None

    def start_db_worker(self):
        """启动数据库工作线程"""
        if self.db_thread is None or not self.db_thread.is_alive():
            self.db_thread = threading.Thread(target=self._db_worker, daemon=True)
            self.db_thread.start()
            logger.info("数据库工作线程已启动")

    def _db_worker(self):
        """数据库工作线程"""
        while True:
            task = self.db_task_queue.get()
            if task is None:
                break
            try:
                task()
            except Exception as e:
                logger.error(f"数据库任务执行失败: {e}")
            finally:
                self.db_task_queue.task_done()

    def stop_db_worker(self):
        """停止数据库工作线程"""
        if self.db_thread and self.db_thread.is_alive():
            self.db_task_queue.put(None)
            self.db_thread.join()
            logger.info("数据库工作线程已停止")

    def create_safe_db_operation(self):
        """创建安全的数据库操作函数"""
        def safe_db_operation(func):
            """安全的数据库操作"""
            self.db_task_queue.put(func)
        return safe_db_operation

# 全局应用状态
app_state = AppState()